package org.mq.mymq.nameserver.event.listener;

import com.alibaba.fastjson.JSON;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.enums.NameServerEventCode;
import org.mq.mymq.common.event.Listener;
import org.mq.mymq.nameserver.common.CommonCache;
import org.mq.mymq.nameserver.event.model.ReplicationMsgEvent;
import org.mq.mymq.nameserver.event.model.SlaveReplicationMsgAckEvent;
import org.mq.mymq.nameserver.store.ServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName ReplicationMsgListener
 * @Description 分片数据同步事件监听器
 * @Author jiarong_ye
 * @Date 2025/6/23 10:04
 * @Version 1.0
 */
public class SlaveReplicationMsgListener implements Listener<ReplicationMsgEvent> {
    private static final Logger log = LoggerFactory.getLogger(SlaveReplicationMsgListener.class);

    @Override
    public void onReceive(ReplicationMsgEvent event) throws Exception {
        ServiceInstance serviceInstance = event.getServiceInstance();
        CommonCache.getServiceInstanceManager().put(serviceInstance);
        log.info("从节点接收到主节点数据");
        String masterEventId = event.getMsgId();
        SlaveReplicationMsgAckEvent slaveReplicationMsgAckEvent = new SlaveReplicationMsgAckEvent();
        slaveReplicationMsgAckEvent.setMsgId(masterEventId);
        event.getChannelHandlerContext().writeAndFlush(new TcpMsg(NameServerEventCode.SLAVE_APPLICATION_ACK_MSG.getCode(),
                JSON.toJSONBytes(slaveReplicationMsgAckEvent)));
    }
}
